import { isFinite, trim } from "lodash";
import React, { useState, useEffect } from "react";
import { Progress } from 'antd';
import cx from "classnames";
import resizeObserver from "@/services/resizeObserver";
import { RendererPropTypes } from "@/visualizations/prop-types";
import { Flip, Clock, DownClock } from "./flip";

import { getCounterData } from "./utils";

import "./render.less";

function getCounterStyles(scale) {
  return {
    msTransform: `scale(${scale})`,
    MozTransform: `scale(${scale})`,
    WebkitTransform: `scale(${scale})`,
    transform: `scale(${scale})`,
  };
}

function getCounterScale(container) {
  const inner = container.firstChild;
  const scale = Math.min(container.offsetWidth / inner.offsetWidth, container.offsetHeight / inner.offsetHeight);
  return Number(isFinite(scale) ? scale : 1).toFixed(2); // keep only two decimal places
}

export default function Renderer({ data, options, visualizationName }) {
  const [scale, setScale] = useState("1.00");
  const [container, setContainer] = useState(null);
  const showPortal = window.location.search.includes("show_portal") && localStorage.getItem('colorstyle_mode');

  useEffect(() => {
    if (container) {
      const unwatch = resizeObserver(container, () => {
        setScale(getCounterScale(container));
      });
      return unwatch;
    }
  }, [container]);

  useEffect(() => {
    if (container) {
      // update scaling when options or data change (new formatting, values, etc.
      // may change inner container dimensions which will not be tracked by `resizeObserver`);
      setScale(getCounterScale(container));
    }
  }, [data, options, container]);

  var strokeColor = {
    from: '#108ee9',
    to: '#87d068',
  }

  if(!!options.minColor) strokeColor.from = options.minColor
  if(!!options.maxColor) strokeColor.to = options.maxColor

  const {
    showTrend,
    trendPositive,
    counterValue,
    counterValueTooltip,
    targetValue,
    targetValueTooltip,
    counterLabel,
    percentValue,
    targetLabel,
  } = getCounterData(data.rows, options, visualizationName);

  const portalstyle = {background: "#00000000", color: localStorage.getItem('colorstyle_color')};
  const isText = !!options.percentProcess ? false : true;
  const isProcess = !!options.percentProcess && (options.percentProcess === 'line' || options.percentProcess === 'circle' || options.percentProcess === 'dashboard') ? true : false;
  const isFlipText = !!options.percentProcess && (options.percentProcess === 'flip' ? true : false);
  const isFlipClock = !!options.percentProcess && (options.percentProcess === 'clock' ? true : false);
  const isFlipDownClock = !!options.percentProcess && (options.percentProcess === 'downclock' ? true : false);

  var counterTitle = !counterLabel ? '' : counterLabel;
  if (isFlipClock && counterTitle === '') {
    const d = new Date();
    const weeks = ['日','一','二','三','四','五','六'];
    counterTitle = d.getFullYear() + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日  星期' + weeks[d.getDay()]
  }

  return (
    <div
      className={cx("counter-visualization-container", {
        "trend-positive": showTrend && trendPositive,
        "trend-negative": showTrend && !trendPositive,
      })}>
      <div className="counter-visualization-content" ref={setContainer}
        style={showPortal ? portalstyle : null}>
        <div style={getCounterStyles(scale)}>
          {!!trim(counterTitle) && (
            <div className="counter-visualization-label" style={!!options.labelAlign ? {textAlign: options.labelAlign} : null} >
              {counterTitle}
            </div>
          )}
          {isProcess && !!options.showPercent && (
            <div style={{ minWidth: 60 }}>
              <Progress percent={percentValue} 
                type={options.percentProcess}
                strokeColor={strokeColor}
                showInfo="true" 
                successPercent={!!options.successPercent ? parseInt(options.successPercent) : 0}                
              />
            </div>
          )}
          {isProcess && !options.showPercent && (
            <div style={{ minWidth: 60 }}>
              <Progress percent={percentValue} 
                type={options.percentProcess}
                strokeColor={strokeColor}
                showInfo="true"
                format={() => counterValue } 
                successPercent={!!options.successPercent ? parseInt(options.successPercent) : 0}                
              />
            </div>
          )}
          {isText && (
            <div className="counter-visualization-value" title={counterValueTooltip}>
              {counterValue}
            </div>
          )}
          {isFlipText && (
            <div className="counter-visualization-value" title={counterValueTooltip}>
              <Flip value={counterValue} />
            </div>
          )}
          {isFlipClock && (
            <div className="counter-visualization-value" title={counterValueTooltip}>
              <Clock />
            </div>
          )}
          {isFlipDownClock && (
            <div className="counter-visualization-value" title={counterValueTooltip}>
              <DownClock deadline={options.downclock} />
            </div>
          )}
          {options.formatTargetValue && targetValue && (
            <div className="counter-visualization-label" title={targetValueTooltip}
            style={!!options.targetAlign ? {textAlign: options.targetAlign} : null} >
              {targetLabel}{targetValue}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Renderer.propTypes = RendererPropTypes;
